package org.ami.onlineschool.dataAccess;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 * Abstract class to support data storage.
 * @author Faraz Ahmed
 *
 * @param <T>
 */
abstract class AbstractDataAccess<T> {

	private final String storageXmlFile;
	private final String dirPath;
	private T targetObject;

	AbstractDataAccess(String dirPath, String storageXmlFile) {
		this.dirPath = dirPath;
		this.storageXmlFile = storageXmlFile;
		try {
			loadTargetObjectFromDisk();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	private void loadTargetObjectFromDisk() throws FileNotFoundException {

		if(new File(dirPath + storageXmlFile).exists()) {
			XMLDecoder d = new XMLDecoder(
					new BufferedInputStream(
							new FileInputStream(dirPath + storageXmlFile)));
			targetObject = (T) d.readObject();
			d.close();
		} else {
			targetObject = initializeTargetObject();
			saveTargetObjectToDisk();
		}
		
	}

	protected abstract T initializeTargetObject();

	protected void saveTargetObjectToDisk() throws FileNotFoundException
	{
		XMLEncoder e = new XMLEncoder(
				new BufferedOutputStream(
						new FileOutputStream(dirPath + storageXmlFile)));


		e.writeObject(targetObject);
		e.close();
	}

	protected T getTargetObject() {
		return targetObject;
	}

	public String getDirPath() {
		return dirPath;
	}

}
